import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start() // 开启进度条
  const token = store.state.user.token
  if (token) {
    if
    // (!store.state.user.userInfo.userID) 不方便访问，映射到全局getters中
    (!store.getters.userID) {
      // 有token才有获取数据的需求，没有token获取数据没有意义
      // 为什么要写await 因为我们想获取完资料再去放行
      // 动态添加路由
      const { roles: { menus = [] }} = await store.dispatch('user/getUserInfoAction')
      // console.log(menus)
      const newRoutes = await store.dispatch('permission/filtersRoutes', menus)
      router.addRoutes([...newRoutes, { path: '*', redirect: '/404', hidden: true }])
      next(to.path)
    }
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})
router.afterEach(() => {
  NProgress.done()
})
